package com.sf.ams.biz.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sf.ams.biz.IDBConnectorBiz;
import com.sf.ams.biz.IString2SqlParserBiz;
import com.sf.ams.constant.Constant;
import com.sf.ams.entity.DBConnectorParamter;
import com.sf.ams.entity.Response;
import com.sf.ams.utils.StringUtil;

/**
 * 描述：数据库连接器，提供执行方法
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年9月27日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
@Service("dBConnectorBiz")
public class DBConnectorBizImpl implements IDBConnectorBiz{
	@Autowired
	private IString2SqlParserBiz string2SqlParserBiz;
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	public Connection getConnection(DBConnectorParamter paramter) {
		 Connection conn = null;
		 try {
			Class.forName(paramter.getDriver());
			conn = DriverManager.getConnection(paramter.getUrl(),paramter.getUsername(),paramter.getPassword());
		} catch (ClassNotFoundException e) {
			logger.error("class {} not found",paramter.getDriver(),e);
		} catch (SQLException e) {
			logger.error("SQLException",e);
		}
		return conn;
	}
	/**
	 * 批量执行sql,一个SQL相当于一个文件中的所有sql
	 * @param sqls Map key 表示文件名的索引，value文件里的sql
	 */
	@Override
	public Response executeBatchSql(Map<Integer,String> sqls,Integer nextIndex,Connection conn) {
		if (conn == null)  return new Response(Response.STATUS_FAIL,"无法获得数据库链接，请检查您的数据库链接串、用户名和密码！",-1);
		if (sqls == null || sqls.isEmpty()) return new Response(Response.STATUS_FAIL,"NoBigIndex",nextIndex);
		Statement psmt = null;
		Integer currentIndex = -1;
		String currentSql = "";
		boolean result = false;
		String failReason = "";
		try {
			Set<Entry<Integer, String>> entrySet = sqls.entrySet();
			Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
			
			while(iterator.hasNext()){
				Entry<Integer,String> entry = iterator.next();
				currentIndex = entry.getKey();
				currentSql = entry.getValue();
				
				List<String> sqlList =  string2SqlParserBiz.parse(currentSql);
				psmt = conn.createStatement();
				for(String sql : sqlList) {
					if (!"".equals(sql.trim()) && !"\r\n".equals(sql)){
						logger.info("脚本[{}]",sql);
						psmt.addBatch(sql);
					}
				}
				currentSql = entry.getValue();
				if(StringUtil.isEmpty(currentSql))continue; 
				logger.info("正在执行SQL[{}]",currentSql);
				psmt.executeBatch();
				result = true;
			}
		} catch (Exception e) {
			logger.error("execute sql [{}] error" ,currentSql,e);
			failReason = e.getMessage().replaceAll(Constant.SEQUENCE_SPLIT, " ");
			result = false;
			return new Response(result?Response.STATUS_SUCCESS:Response.STATUS_FAIL,failReason,currentIndex);
		}finally{
			try {
				if (psmt != null){
					psmt.close();
				}
				if(conn != null) {
					conn.close();
				}
				
			} catch (SQLException e) {
				logger.error("close connnection error");
			}
		}
		return new Response(result?Response.STATUS_SUCCESS:Response.STATUS_FAIL,failReason,currentIndex);
	}
	

}
